package com.luo.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.luo.ssm.entity.SysFolder;
import com.luo.ssm.entity.SysUser;
import com.luo.ssm.service.SysFolderService;
import com.luo.ssm.vo.FolderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * @author : luocheng
 * @date : Created in 2021/8/28 23:16
 * @description :
 */
@Controller
@RequestMapping("/folderManage")
public class SysFolderController {
    @Autowired
    private SysFolderService sysFolderService;
    @RequestMapping(value = "/list/{uid}",params = "uid!=-1")
    public String list(Model model, FolderVo folderVo,@RequestParam(value = "currentPage",required = false,defaultValue = "1") int pageNum, @RequestParam(required = false,defaultValue = "5") int pageSize){
        PageInfo<SysFolder> pageInfo = sysFolderService.getAllFolder(folderVo, pageNum, pageSize);
        model.addAttribute("pageInfo",pageInfo);
        //存储查询关键字用于回显
        model.addAttribute("keyword",folderVo.getKeyword());
        return "dir/list";
    }

    @RequestMapping("/add")
    public String add(FolderVo folderVo, HttpSession session){
        //获取文件夹名
        String tname = folderVo.getTname();
        //从session中获取登录名
        SysUser user = (SysUser) session.getAttribute("user");
        String uloginname = user.getUloginname();
        //完整文件夹名
        String fullFolderName="upload/"+uloginname+"/"+tname;
        //根据文件名获取真实路径
        String realPath = session.getServletContext().getRealPath("/" + fullFolderName);
        //若文件夹不存在，则创建文件夹
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
            //向数据库中存入信息
            int i = sysFolderService.addNewFolderInfo(folderVo);
            return "redirect:/folderManage/list/"+user.getUid();
        }else {
            //若存在，则重定向到list页面
            return "redirect:/folderManage/list"+user.getUid();
        }

    }
}
